import { reactive } from 'vue'
import axios from '@/utils/request'

// 创建全局权限状态管理对象
export const permissions = reactive({
  permissionData: {},
  
  // 获取权限的方法
  async fetchPermissions() {
    try {
      const response = await axios.get('/api/admin/permissions')
      if (response.data.code === 1) {
        this.permissionData = response.data.data
        console.log('获取到的权限信息:', this.permissionData)
      } else {
        console.error('获取权限失败:', response.data.msg)
      }
    } catch (error) {
      console.error('获取权限出错:', error)
      // 如果获取失败，清空权限
      this.permissionData = {}
    }
  },

  // 检查学生编辑权限
  hasStudentEditPermission() {
    return this.permissionData.studentEdit === true
  },

  // 检查教师编辑权限
  hasTeacherEditPermission() {
    return this.permissionData.teacherEdit === true
  },

  // 检查用户是否有编辑个人资料的权限
  hasProfileEditPermission() {
    return this.permissionData.canEditProfile === true
  },

  // 初始化权限
  async initialize() {
    await this.fetchPermissions()
  }
})

// 导出便捷方法
export const fetchPermissions = () => permissions.fetchPermissions()
export const initializePermissions = () => permissions.initialize()
